package com.lanju.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.lanju.entity.Contract;
import com.lanju.entity.ExpectedFixedIncome;
import com.lanju.entity.VacantPeriod;

@Repository
public class ContractDao {
	
	 private static final Log log = LogFactory.getLog(ContractDao.class);
	
	@PersistenceContext(unitName = "financialmarketingUnit")
    private EntityManager entityManager;
	
	public  void createContract(Contract contract){
		try {
			entityManager.persist(contract);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void delContract(Contract contract){
		try {
			entityManager.remove(contract);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Contract getContract(Map<String,Object> map){
		try {
			return entityManager.find(Contract.class, map.get("contractId").toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List<VacantPeriod> getVacantPeriodList(Map<String,Object> map){
		try {
			StringBuffer sql=new StringBuffer();
			sql.append("from VacantPeriod where contractId='"+map.get("contractId").toString()+"' order by startTime asc");
			Query query=entityManager.createQuery(sql.toString());
			return query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List<ExpectedFixedIncome> getExpectedFixedIncomeList(Map<String,Object> map){
		try {
			StringBuffer sql=new StringBuffer();
			sql.append("from ExpectedFixedIncome where contractId='"+map.get("contractId").toString()+"' order by expectedStartTime asc");
			Query query=entityManager.createQuery(sql.toString());
			return query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void updateConstract(Contract contract){
		try {
			entityManager.merge(contract);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public List<Contract> getContractList(Map<String,Object> map){
		try {
			StringBuffer sql=new StringBuffer();
			sql.append(" from Contract where userId='"+map.get("userId").toString()+"' order by createTime desc");
			Query query=entityManager.createQuery(sql.toString());
			List<Contract> list=query.getResultList();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public Contract signComtract(Contract contract){
		try {
			return entityManager.merge(contract);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
